# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 生产者-事务机制(异常).py
# @Author: dongguangwen
# @Date  : 2025-04-12 15:10
import pika


# 连接参数
credentials = pika.PlainCredentials('admin', 'password')
connection = pika.BlockingConnection(
    pika.ConnectionParameters('192.168.1.119', credentials=credentials, virtual_host='my_vhost'))
channel = connection.channel()

# 声明交换器和队列
channel.exchange_declare(exchange='tx_exchange', exchange_type='direct', durable=True)
channel.queue_declare(queue='tx_queue', durable=True)
channel.queue_bind(queue='tx_queue', exchange='tx_exchange', routing_key='tx_key')

try:
    channel.tx_select()
    # 模拟发送消息
    channel.basic_publish(
        exchange='tx_exchange',
        routing_key='tx_key',
        body='这个消息将不会提交'
    )

    raise Exception("模拟异常 ❌")

    channel.tx_commit()

except Exception as e:
    print("[‼️] 模拟异常，事务回滚")
    channel.tx_rollback()

finally:
    connection.close()
